package com.bolins.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	public static void setCookie(HttpServletRequest req,
			HttpServletResponse res, String name, String value) {
		if (isCookieExisted(req, name)) {
			updateCookie(req, res, name, value);
		} else {
			Cookie cookie = new Cookie(name, value);
			cookie.setMaxAge(60 * 60);
			res.addCookie(cookie);
		}
	}

	public static void updateCookie(HttpServletRequest req,
			HttpServletResponse res, String name, String value) {
		if (!isCookieExisted(req, name))
			throw new RuntimeException("No Cookie to update");

		Cookie cookie = getCookie(req, name);
		cookie.setValue(value);
		cookie.setMaxAge(60 * 60);
		res.addCookie(cookie);
	}

	public static Cookie getCookie(HttpServletRequest req, String name) {
		Cookie[] cookieArr = req.getCookies();
		for (Cookie cookie : cookieArr) {
			if (cookie.getName().equals(name)) {
				return cookie;
			}
		}
		return null;
	}

	public static void removeCookie(HttpServletRequest req,
			HttpServletResponse res, String name) {
		Cookie cookie = getCookie(req, name);
		cookie.setMaxAge(0);
		res.addCookie(cookie);
	}

	public static String getCookieValue(HttpServletRequest req, String name) {
		Cookie[] cookieArr = req.getCookies();
		for (Cookie cookie : cookieArr) {
			if (cookie.getName().equals(name)) {
				return cookie.getValue();
			}
		}
		return null;
	}

	public static Boolean isCookieExisted(HttpServletRequest req, String name) {
		Cookie[] cookieArr = req.getCookies();
		for (Cookie cookie : cookieArr) {
			if (cookie.getName().equals(name)) {
				return true;
			}
		}
		return false;
	}
}
